import 'dart:io';
import 'package:dio/dio.dart' as dio;
import 'package:http_parser/http_parser.dart';
import 'package:logger/logger.dart';
import 'package:merchants/services/base-service.dart';

class CommonUploadService extends BaseService {
  CommonUploadService({required super.ref});

  final Logger _logger = Logger();

  Future<List<String>> uploadImages(
    List<File> images, {
    required String directory,
  }) async {
    try {
      final files = <dio.MultipartFile>[];

      // Prepare multipart files
      for (var i = 0; i < images.length; i++) {
        final file = images[i];
        final ext = file.path.split('.').last.toLowerCase();
        String contentType;

        switch (ext) {
          case 'jpg':
          case 'jpeg':
            contentType = 'image/jpeg';
            break;
          case 'png':
            contentType = 'image/png';
            break;
          case 'gif':
            contentType = 'image/gif';
            break;
          default:
            contentType = 'application/octet-stream';
        }

        final multipartFile = await dio.MultipartFile.fromFile(
          file.path,
          filename: 'image_$i.$ext',
          contentType: MediaType.parse(contentType),
        );
        files.add(multipartFile);
      }

      // Send multipart request
      final response = await multipartPost(
        '/admin/common/upload/images',
        fields: {'directory': directory},
        files: files,
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '上传失败');
          }
          final data = json['data'];
          if (data is List) {
            // 直接返回后端返回的URL
            return data.map((item) => item?.toString() ?? '').toList();
          } else {
            throw ApiException('响应数据格式错误：data 不是列表');
          }
        },
      );
      return response;
    } catch (e) {
      _logger.e(e);
      throw ApiException('上传图片失败: $e');
    }
  }

  /// Upload a single image
  Future<String> uploadImage(File image, {required String directory}) async {
    try {
      final ext = image.path.split('.').last.toLowerCase();
      String contentType;

      switch (ext) {
        case 'jpg':
        case 'jpeg':
          contentType = 'image/jpeg';
          break;
        case 'png':
          contentType = 'image/png';
          break;
        case 'gif':
          contentType = 'image/gif';
          break;
        default:
          contentType = 'application/octet-stream';
      }
      final multipartFile = await dio.MultipartFile.fromFile(
        image.path,
        filename: 'image.$ext',
        contentType: MediaType.parse(contentType),
      );

      final response = await multipartPost<String>(
        '/admin/common/upload/image',
        fields: {'directory': directory},
        files: [multipartFile],
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '上传失败');
          }
          final data = json['data'];
          if (data is List && data.isNotEmpty) {
            return data.first?.toString() ?? '';
          } else {
            throw ApiException('响应数据格式错误：data 字段缺失或为空');
          }
        },
      );

      return response;
    } catch (e) {
      rethrow;
    }
  }
}
